package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 *
 * @author zs
 * @date 2025-10-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警过滤
     */
    @Override
    public void alertFilter() {
        Long count = lambdaQuery().eq(AlertRule::getStatus, 1)
                .count();
        if (count == null || count == 0) {
            log.info("没有启用的报警规则");
            return;
        }

        //查出最新的设备数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);

        if (StringUtils.isEmpty(values)) {
            log.info("没有设备数据");
            return;
        }
        //创建一个总稽核用来存放所有的设备数据
        List<DeviceData> alldeviceDatas = new ArrayList<>();

        for (Object value : values) {
            String json = (String) value;
            //反序列化
            List<DeviceData> deviceDataList = JSONUtil.toList(json, DeviceData.class);
            alldeviceDatas.addAll(deviceDataList);
        }

        alldeviceDatas.forEach(this::alertFilter);
    }


    /**
     * 逐条过滤报警数据
     *
     * @param deviceData
     */
    private void alertFilter(DeviceData deviceData) {
        //校验上报时间是否小于1分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
        //准备对应报警规则，查询所有的该产品规则和该物模型规则
        //先查询针对同产品单个设备设置的规则
        LambdaQueryWrapper<AlertRule> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1);
        List<AlertRule> iotRules = alertRuleMapper.selectList(lqw);

        //查询针对同产品所有设备的规则
        LambdaQueryWrapper<AlertRule> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1);
        List<AlertRule> allRules = alertRuleMapper.selectList(lqw1);

        //合并集合
        Collection<AlertRule> allArertRules = CollUtil.addAll(allRules, iotRules);

        //规则判空
        if (StringUtils.isEmpty(allArertRules)) {
            return;
        }

        //遍历每一条规则
        for (AlertRule alertRule : allArertRules) {
            deviceDataAlarmHandler(alertRule, deviceData);
        }

    }

    //规则和设备数据的校验
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        //1.校验是否在生效时间内
        //报警生效时段
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime now = LocalTime.now();
        if (now.isBefore(startTime) || now.isAfter(endTime)) {
            //当前时间报警不生效
            return;
        }


        //2.校验数据是否达到阈值

        //获取IOTID

        String iotId = deviceData.getIotId();
        ////报警次数缓存KEY
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();

        //运算符
        String operator = alertRule.getOperator();
        //阈值
        Double value = alertRule.getValue();
        String dataValue = deviceData.getDataValue();
        int compare = Double.compare(Double.parseDouble(dataValue),value);
        if ((alertRule.getOperator().equals(">=") && compare >= 0) || (alertRule.getOperator().equals("<") && compare < 0)) {
            log.info("当前上报的数据符合规则异常");
        } else {
            //正常的数据
            redisTemplate.delete(aggCountKey);
            return;
        }
        //3.redis中查询沉默周期
        //沉默周期缓存KEY
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        String s = redisTemplate.opsForValue().get(silentKey);
        if (StringUtils.isNotEmpty(silentData)) {
            // 在redis中查到了沉默周期缓存，不允许报警
            return;
        }
        //在redis中没有查到沉默周期缓存，允许报警，但是还得校验报警次数
        //4.查询报警次数
        String aggData = redisTemplate.opsForValue().get(aggCountKey);
        int count = StringUtils.isEmpty(aggData) ? 1 : Integer.parseInt(aggData) + 1;
        //持续周期
        Integer duration = alertRule.getDuration();
        if (duration != count) {
            //持续周期未到，暂不报警
            redisTemplate.opsForValue().set(aggCountKey, count + "");
            return;
        }
        //持续周期到了，允许报警，删除之前的持续周期缓存
        redisTemplate.delete(aggCountKey);
        //新增沉默周期缓存
        redisTemplate.opsForValue().set(silentKey, "aaa", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //发送报警
        //先判断是否是老人数据，拿到需要报警的所有用户的id
        List<Long> userIds = new ArrayList<>();
        if (alertRule.getAlertDataType() == 0) {
            //是老人数据
            //还需在再判断是否是关于老人的固定设备数据2
            if (deviceData.getLocationType() == 0) {
                //是老人的数据，直接通过老人查询护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else {
                //是床位的数据，通过床位查找查找老人，再通过老人查找护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        } else {
            //是房间固定设备数据，查找维修员
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }

        //查找超级管理员
        List<Long> longs = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        Collection<Long> allUserIds = CollUtil.addAll(userIds, longs);
        //去重
        allUserIds = CollUtil.distinct(allUserIds);

        //保存报警数据
        saveAlertData(deviceData, allUserIds, alertRule);
    }

    @Autowired
    private AlertDataServiceImpl alertDataService;

    /**
     * 保存报警数据
     *
     * @param deviceData
     * @param allUserIds
     * @param alertRule
     */
    private void saveAlertData(DeviceData deviceData, Collection<Long> allUserIds, AlertRule alertRule) {
        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setId(null);
        alertData.setAlertRuleId(alertRule.getId());
        //报警原因
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setAlertRuleId(alertRule.getId());
        List<AlertData> alertDataList = allUserIds.stream().map(userId -> {
            AlertData alertData1 = BeanUtil.toBean(alertData, AlertData.class);
            alertData1.setUserId(userId);
            return alertData1;
        }).collect(Collectors.toList());

        //保存报警数据
        alertDataService.saveBatch(alertDataList);
    }
}
